package com.gitee.mall.sentinel;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreRunner {

    public static void main(String[] args) {
        //每次只能通过3个
        Semaphore semaphore = new Semaphore(1);
        for (int i = 0; i < 10; i++) {
            new Thread(new Worker(semaphore)).start();
        }
    }

    static class Worker implements Runnable {
        private final Semaphore semaphore;

        public Worker(Semaphore semaphore) {
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                if (semaphore.tryAcquire(500, TimeUnit.MILLISECONDS)) {
                    System.out.println("进入--------》");
                    TimeUnit.SECONDS.sleep(1);
                    semaphore.release();
                } else {
                    System.out.println("服务降级------》");
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}
